<template>
    <div class="category-detail-container">
        <h2>{{ categoryId }}</h2>
        <el-empty v-if="categories.length === 0" description="No product data is available" />
        <div v-else>
            <div class="category-menu">
                <div v-for="(category, index) in categories" :key="category.id" 
                    class="menu-item-wrapper">
                    <div class="menu-item" 
                         :class="{ active: index == activeIndex }"
                         @click="loadProductsData(index); activeIndex = index">
                        {{ category.name }}
                    </div>
                </div>
            </div>
            <el-divider />
            <div class="products-container">
                <el-empty v-if="loading" description="Loading...">
                    <el-icon class="loading">
                        <Loading />
                    </el-icon>
                </el-empty>
                <el-empty v-else-if="products.length === 0" description="No product data is available" />
                <el-row v-else :gutter="20">
                    <el-col v-for="product in products" :key="product.id" :xs="24" :sm="12" :md="8" :lg="6">
                        <el-card class="product-card" shadow="hover">
                            <div class="product-content">
                                <h3>ID:<span style="color: blue;"> {{ product.id }}</span></h3>
                                <p>{{ product.description }}</p>
                                <p>price: ¥{{ product.price }}</p>
                                <el-button type="primary" size="large" class="add-cart"
                                    @click="showDrawer(product.id)">add to cart</el-button>
                                <el-button type="primary" size="small" class="detail"
                                    @click="viewDetail(product.id)">View details</el-button>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </div>
    </div>
    <el-drawer v-model="drawer" title="Please select the number to add" :direction="direction"
        :before-close="handleClose" size="15%" :with-header="false">
        <div class="drawer-content">
            <h3>Please select the number to add:</h3>
            <div class="quantity-control">
                <el-input-number v-model="quantity" :min="1" :max="99" size="large" @change="handleQuantityChange" />
            </div>
            <div class="confirm-button">
                <el-button type="primary" size="large" @click="handleAddToCart">
                    add
                </el-button>
            </div>
        </div>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import apiClient from '@/api/api'
import store from '@/store'


const route = useRoute()
// 获取路径参数
const categoryId = computed(() => route.params.categoryId as string)
const loading = ref(false)
// 用户是否登录
const isLoggedIn = ref(store.getters.getLoginStatus)
// 弹出层
const drawer = ref(false)
// 弹出层方向
const direction = ref('btt')
// 选中的product id
const productId = ref('')
// 添加购物车的数量
const quantity = ref(1)
// 关闭弹出层
const handleClose = (done: () => void) => {
    quantity.value = 1
    productId.value = ''
    done()
}
// 显示弹出层
const showDrawer = (id: string) => {
    if (!isLoggedIn.value) {
        ElMessage.warning('请先登录')
        return
    }
    drawer.value = true
    productId.value = id
}
// 加入购物车数量变化
const handleQuantityChange = (value: number) => {
    quantity.value = value
}
// 处理不同分类
const activeIndex = ref(0)
const handleSelect = (key: number, keyPath: string[]) => {
    //console.log("key:", key)
    loadProductsData(key)
    activeIndex.value = key
}

// 分类数据
const categories = ref<Array<{ id: string, name: string }>>([]);

// 加载分类数据的函数
const loadCategoriesData = async () => {
    categories.value = []
    // 发送真实请求
    await apiClient.get(`/categories/${categoryId.value}/products`)
        .then((response) => {
            if (response.data.status === 0) {
                const length: number = response.data.data.length
                for (let i = 0; i < length; i++) {
                    categories.value.push({
                        id: response.data.data[i].productId,
                        name: response.data.data[i].name,
                    })
                }
            } else {
                ElMessage({
                    message: response.data.message,
                    type: 'error'
                })
            }
        })
        .catch((error) => {
            ElMessage({
                message: error.message,
                type: 'error'
            })
        })
}
// 产品数据
const products = ref<Array<{ id: string, description: string, price: number, cateId: string }>>([]);
// 加载产品数据的函数
const loadProductsData = async (index: number) => {
    try {
        // 清空之前的数据
        products.value = []
        loading.value = true
        // 获取分类id
        const cateId = categories.value[index].id

        // 发送真实请求
        apiClient.get(`/products/${cateId}/items`)
            .then((response) => {
                if (response.data.status === 0) {
                    const length: number = response.data.data.length
                    products.value = [] // 清空之前的数据，防止数据重复添加
                    // 遍历响应数据，将每个产品添加到products数组中
                    for (let i = 0; i < length; i++) {
                        products.value.push({
                            id: response.data.data[i].itemId,
                            description: response.data.data[i].description,
                            price: response.data.data[i].listPrice,
                            cateId: cateId
                        })
                    }
                } else {
                    ElMessage({
                        message: response.data.message,
                        type: 'error'
                    })
                }
            })
    } catch (error: any) {
        ElMessage({
            message: error.message,
            type: 'error'
        })
    } finally {
        loading.value = false
    }
}
// 初始加载数据
onMounted(async () => {
    try {
        await loadCategoriesData();
        if (categories.value.length > 0) {
            await loadProductsData(activeIndex.value);
        }
    } catch (error) {
        ElMessage.error('加载数据失败');
    }
})

// 监听路由参数变化，当分类ID变化时重新加载数据
watch(() => route.params.categoryId, (newCategoryId, oldCategoryId) => {
    if (newCategoryId !== oldCategoryId) {
        loadCategoriesData()
    }
}, { immediate: false })

// 添加商品到购物车

const handleAddToCart = async() => {
    // 发送请求到后端，将商品添加到购物车
    apiClient.post(`/carts?itemId=${productId.value}`)
        .then((response) => {
            if (response.data.status === 0) {
                ElMessage({
                    message: '商品已添加到购物车',
                    type: 'success'
                })
            } else {
                ElMessage({
                    message: response.data.message,
                    type: 'error'
                })
            }
        })
        .catch((error) => {
            ElMessage({
                message: error.message,
                type: 'error'
            })
        })
}
       
        

// 查看详情
const viewDetail = (productId: string) => {
    // TODO 
}
</script>

<style scoped>
.category-detail-container {
    padding: 20px;
    width: 60%;
}

.el-menu-demo {
    margin-bottom: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-menu-demo .el-menu-item {
    margin-left: 20px;
    margin-right: 20px;
}

.description {
    color: #666;
    margin-bottom: 20px;
}

.products-container {
    margin-top: 20px;
}

.product-card {
    margin-bottom: 20px;
    transition: transform 0.3s ease;
    height: 100%;
}

.product-card:hover {
    transform: translateY(-5px);
}

.product-content {
    text-align: center;
    padding: 15px;
}

.product-content h3 {
    font-size: 1.2rem;
    color: #2c3e50;
    margin-bottom: 12px;
}

.product-content p {
    font-size: 1rem;
    color: #666;
    line-height: 1.5;
    margin-bottom: 8px;
}

.product-content p:last-of-type {
    font-size: 1.1rem;
    color: #e6a23c;
    font-weight: 600;
    margin-bottom: 15px;
}

.product-image {
    width: 100px;
    height: auto;
    margin-bottom: 10px;
}

.loading {
    font-size: 20px;
    animation: rotating 2s linear infinite;
}

.add-cart {
    margin-top: 10px;
    margin-bottom: 10px;
    color: white;
    background-color: #0c8745;
    transition: all 0.3s ease;
    border-radius: 5px;
    padding: 8px 16px;
    font-size: 16px;
}

.add-cart:hover {
    transform: scale(1.05);
    background-color: #0da553;
    box-shadow: 0 2px 12px rgba(12, 135, 69, 0.2);
}

.add-cart:active {
    transform: scale(0.95);
    background-color: #0a7339;
}

.detail {
    margin-top: 10px;
    margin-bottom: 10px;
    color: rgb(18, 144, 227);
    border: none;
    background-color: transparent;
    text-align: center;
    text-decoration: underline;
    font-family: Arial, sans-serif;
    transition: all 0.3s ease;
    margin-right: 10px;
}

.detail:hover {
    color: rgb(12, 110, 175);
    transform: translateY(-2px);
}

.detail:active {
    transform: translateY(0);
    color: rgb(8, 82, 131);
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

/* 购物车抽屉样式 */
.drawer-content {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 20px;
    gap: 15px;
}

.drawer-content h3 {
    flex: auto;
    display: flex;
    justify-content: flex-start;
    margin-right: 10px;
}

.quantity-control {
    flex: auto;
    display: flex;
    justify-content: flex-end;
}

.confirm-button {
    display: flex;
    align-items: center;
}

/* 菜单样式 */
.category-menu {
    margin-bottom: 20px;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
}

.menu-item-wrapper {
    margin-bottom: 10px;
}

.menu-item {
    text-align: center;
    padding: 10px 15px;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    white-space: nowrap;
    display: inline-block;
}

.menu-item:hover {
    background-color: #ecf5ff;
    color: #409EFF;
}

.menu-item.active {
    background-color: #409EFF;
    color: white;
}
</style>